package com.atguigu.gulimall.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.entity.vo.SeckillInfoVo;
import com.atguigu.gulimall.product.entity.vo.SkuItemSaleAttrVo;
import com.atguigu.gulimall.product.entity.vo.SkuItemVo;
import com.atguigu.gulimall.product.entity.vo.SpuItemAttrGroupVo;
import com.atguigu.gulimall.product.feign.SecKillFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    final SkuImagesService skuImagesService;
    final SpuInfoDescService spuInfoDescService;
    final AttrGroupService attrGroupService;
    final SkuSaleAttrValueService saleAttrValueService;
    final WareFeignService wareFeignService;
    final ThreadPoolExecutor executor;
    final SecKillFeignService secKillFeignService;

    public SkuInfoServiceImpl(SkuImagesService skuImagesService, SpuInfoDescService spuInfoDescService, AttrGroupService attrGroupService, SkuSaleAttrValueService saleAttrValueService, WareFeignService wareFeignService, ThreadPoolExecutor executor, SecKillFeignService secKillFeignService) {
        this.skuImagesService = skuImagesService;
        this.spuInfoDescService = spuInfoDescService;
        this.attrGroupService = attrGroupService;
        this.saleAttrValueService = saleAttrValueService;
        this.wareFeignService = wareFeignService;
        this.executor = executor;
        this.secKillFeignService = secKillFeignService;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        /**
         * key
         * catelogId
         * brandId
         * min
         * max
         */
        String key = (String) params.get("key");
        String catelogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String min = (String) params.get("min");
        String max = (String) params.get("max");
        if (StrUtil.isNotEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        if (StrUtil.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        if (StrUtil.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        BigDecimal decimalMin = new BigDecimal(min);
        if (StrUtil.isNotEmpty(min)) {
            wrapper.ge("price", decimalMin);
        }
        BigDecimal decimalMax = new BigDecimal(max);
        if (StrUtil.isNotEmpty(max) && decimalMax.compareTo(new BigDecimal("0")) == 1) {
            wrapper.le("price", decimalMax);
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        //1.sku基本信息获取  pms_sku_info
        //第一个异步任务
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            //设置是否有货
            Map<Long, Boolean> stockMap = null;
            try {
                R skuHasStock = wareFeignService.getSkuHasStock(Collections.singletonList(info.getSkuId()));
                TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<>() {
                };
                stockMap = skuHasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
            } catch (RuntimeException e) {
                log.error("库存服务查询异常，原因：{}", e);
            }
            Map<Long, Boolean> finalStockMap = stockMap;
            //设置库存信息
            if (finalStockMap == null) {
                skuItemVo.setHasStock(true);
            } else {
                skuItemVo.setHasStock(finalStockMap.get(info.getSkuId()));
            }
            return info;
        }, executor);

        //2.sku图片信息  pms_sku_images
        //第五个异步任务，这个异步任务跟上面的所有任务都没有关系的
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> images = skuImagesService.list(new QueryWrapper<SkuImagesEntity>().lambda().eq(SkuImagesEntity::getSkuId, skuId));
            skuItemVo.setImages(images);
        }, executor);
        //3.获取spu销售属性组合
        //第二个异步任务
        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //3、获取spu的销售属性组合
            //3.1.查出当前spu属于哪个分类，就能知道有哪些分组信息
            List<SkuItemSaleAttrVo> saleAttrsVos = saleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());//获取所有可能的销售属性组合
            skuItemVo.setSaleAttr(saleAttrsVos);
        }, executor);
        //4.获取spu介绍
        //第三个异步任务
        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(res -> {
            //4.获取spu的介绍信息  pms_spu_info_desc
            SpuInfoDescEntity spuDesc = spuInfoDescService.getById(res.getSpuId());//按照spuid来查询spu的介绍信息
            skuItemVo.setDesp(spuDesc);
        }, executor);
        //5.获取spu规格参数
        //第四个异步任务
        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync(res -> {
            //5.获取spu的规格参数信息
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());  //查出某个spu的属性分组信息,以及这个分组里面所有属性对应的值
            skuItemVo.setGroupAttrs(attrGroupVos);
        }, executor);

        //6.查询当前sku是否参与秒杀优惠活动
        //第五个异步任务
        CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
            R seckillInfo = secKillFeignService.getSkuSeckillInfo(skuId);
            if (seckillInfo.getCode() == 0) {
                SeckillInfoVo seckillInfoVo = seckillInfo.getData(new TypeReference<SeckillInfoVo>() {
                });
                skuItemVo.setSeckillInfo(seckillInfoVo);
            }
        }, executor);

        //等待所有任务都完成，此方法就是以上的所有异步任务都做完了以后,才返回数据
        CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imageFuture, secKillFuture).get();
        return skuItemVo;
    }

}